<!--
  Copyright (c) 2018-2999 广州市蓝海创新科技有限公司 All rights reserved.

  https://www.mall4j.com/

  未经允许，不可做商业用途！

  版权所有，侵权必究！
-->

<template>
  <div class="Mall4j login component-login-popup">
    <div class="popup-mask" />
    <div class="login-box">
      <div
        class="close"
        @click="$emit('hideLoginPop')"
      />
      <div class="login-header">
        <div
          :class="['item',loginType==0?'active':'']"
          data-logintype="0"
          :style="{padding:$t('language')=='en'?'0 30px 0 0':'18px'}"
          @click="changeLoginType($event)"
        >
          {{ $t('login.accountLogin') }}
        </div>
        <div
          :class="['item',loginType==1?'active':'']"
          data-logintype="1"
          :style="{padding:$t('language')=='en'?'0 0 0 30px':'18px'}"
          @click="changeLoginType($event)"
        >
          {{ $t('login.mobileLogin') }}
        </div>
      </div>

      <!-- 账号登录 -->
      <div
        v-if="loginType==0"
        class="login-con"
      >
        <div :class="['item','account',errorTips==3?'msg-error':'']">
          <div class="icon" />
          <input
            v-model="userName"
            v-input-rule
            type="text"
            class="input"
            maxlength="11"
            :placeholder="$t('login.enterUsername')"
            @keyup.enter="login"
          >
          <div
            class="cancel"
            data-type="userName"
            @click="clearInput($event)"
          />
        </div>
        <div
          v-show="errorTips == 3"
          class="error"
        >
          {{ $t('ucPassword.enterCorrectNumber') }}
        </div>
        <div :class="['item','password',errorTips==4?'msg-error':'']">
          <div class="icon" />
          <input
            v-model="password"
            v-input-rule
            type="password"
            class="input"
            :placeholder="$t('login.enterPassword')"
            @keyup.enter="login"
          >
          <div
            class="cancel"
            data-type="password"
            @click="clearInput($event)"
          />
        </div>
        <div
          v-show="errorTips == 4"
          class="error"
        >
          {{ $t('login.enterPassword') }}
        </div>
        <a
          href="javascript:void(0)"
          class="login-button"
          @click="login"
        >{{ $t('login.login') }}</a>
        <div :class="['agree-box',$t('language') === 'en'?'agree-box-en':'']">
          <div class="text">
            <el-checkbox
              v-model="isAgree"
              :true-label="true"
              :false-label="false"
            />
          </div>
          <div class="text">
            {{ $t('login.consentOfLoginRepresentative') }}
            <a
              href="javaScript:void(0)"
              class="agreement"
              @click="toTermsPage(0)"
            >{{ $t('login.termsOfService') }}</a>
            {{ $t('login.and') }}
            <a
              href="javaScript:void(0)"
              class="agreement"
              @click="toTermsPage(1)"
            >{{ $t('login.privacyPolicy') }}</a>
          </div>
        </div>
        <div
          v-show="errorTips == 6 && !isAgree"
          class="error"
        >
          {{ $t('login.agreeTerms') }}
        </div>
      </div>
      <!-- /账号登录 -->

      <!-- 手机登录 -->
      <div
        v-if="loginType==1"
        class="login-con"
      >
        <div :class="['item','phone',errorTips==1?'msg-error':'']">
          <div class="icon" />
          <input
            v-model="mobile"
            type="text"
            class="input"
            maxlength="11"
            :placeholder="$t('login.enterPhone')"
            @keyup.enter="login"
          >
          <div
            class="cancel"
            data-type="mobile"
            @click="clearInput($event)"
          />
        </div>
        <div
          v-show="errorTips == 1"
          class="error"
        >
          {{ $t('register.enterValidPhone') }}
        </div>
        <div :class="['item','code',errorTips==2?'msg-error':'']">
          <div class="icon" />
          <input
            v-model="validCode"
            type="text"
            class="input"
            :placeholder="$t('login.enterCode')"
            :style="{width:$t('language')=='en'?'100px':'150px'}"
            @keyup.enter="login"
          >
          <a
            v-show="show"
            href="javascript:void(0);"
            class="send-code"
            :style="{width:$t('language')=='en'?'139px':'89px'}"
            @click="getCode"
          >{{ $t('login.getCode') }}</a>
          <span
            v-show="!show"
            class="send-code"
            :style="{width:$t('language')=='en'?'139px':'89px'}"
            style="cursor: not-allowed;"
          >{{ count }} s</span>
        </div>
        <div
          v-show="errorTips == 2"
          class="error"
        >
          {{ $t('login.enterCode') }}
        </div>
        <a
          href="javascript:void(0)"
          class="login-button"
          @click="login"
        >{{ $t('login.login') }}</a>
        <div :class="['agree-box',$t('language') == 'en'?'agree-box-en':'']">
          <div class="text">
            <el-checkbox
              v-model="isAgree"
              :true-label="true"
              :false-label="false"
            />
          </div>
          <div class="text">
            {{ $t('login.consentOfLoginRepresentative') }}
            <a
              href="javaScript:void(0)"
              class="agreement"
              @click="toTermsPage(0)"
            >{{ $t('login.termsOfService') }}</a>
            {{ $t('login.and') }}
            <a
              href="javaScript:void(0)"
              class="agreement"
              @click="toTermsPage(1)"
            >{{ $t('login.privacyPolicy') }}</a>
          </div>
        </div>
        <div
          v-show="errorTips == 6 && !isAgree"
          class="error"
        >
          {{ $t('login.agreeTerms') }}
        </div>
      </div>
      <!-- /手机登录 -->

      <div class="login-footer">
        <router-link
          class="footer-a"
          to="/register"
        >
          {{ $t('register.registerNow') }}
        </router-link>
        <router-link
          to="/forget-password"
          class="footer-a"
        >
          {{ $t('login.forgotYourPassword') }}
        </router-link>
      </div>
    </div>
  </div>
</template>

<script setup>
import cookie from 'vue-cookies'
import * as util from '@/utils/index.js'

const router = useRouter()

// 1-手机登录 0-账号登录
const loginType = ref(0)
// 输入错误提示 =  1-手机号输入错误  2-验证码输入错误  3-账号输入错误  4-密码输入错误 5-图形验证码错误 6-未同意条款
const errorTips = ref(0)
const mobile = ref('')
const validCode = ref('')
const userName = ref('')
const password = ref('')
const imgValid = ref('')
/**
 * 切换登录方式
 */
const changeLoginType = (e) => {
  loginType.value = e.target.dataset.logintype - 0
  errorTips.value = 0
  mobile.value = ''
  validCode.value = ''
  userName.value = ''
  password.value = ''
  imgValid.value = ''
}

const hadGotCode = ref(false)
// 验证码相关
const show = ref(true)
const count = ref(null)
const timer = ref(null)
/**
 * 获取登录验证码
 */
const getCode = () => {
  if (!checkPhoneNumber(mobile.value)) {
    errorTips.value = 1
    return
  }
  if (hadGotCode.value) {
    return
  }
  if (!isAgree.value) {
    errorTips.value = 6
    return
  }
  hadGotCode.value = true
  errorTips.value = 0
  http({
    url: '/sms/sendLoginCode',
    method: 'POST',
    data: {
      mobile: mobile.value
    }
  }).then(() => {
    const timeCount = 60
    if (!timer.value) {
      count.value = timeCount
      show.value = false
      timer.value = setInterval(() => {
        if (count.value > 0 && count.value <= timeCount) {
          count.value--
        } else {
          show.value = true
          clearInterval(timer.value)
          timer.value = null
          hadGotCode.value = false
        }
      }, 1000)
    }
  }).catch(() => {
    hadGotCode.value = false
  })
}

const userStore = useUserStore()
const isAgree = ref(true) // 是否同意条款
const isLogging = ref(false)
const emit = defineEmits(['hideLoginPop'])
/**
 * 登录
 */
const login = util.debounce(() => {
  userName.value = userName.value.trim()
  mobile.value = mobile.value.trim()
  if (loginType.value == 1) {
    // 手机验证码登录
    if (!checkPhoneNumber(mobile.value)) {
      errorTips.value = 1
      return
    } else if (!validCode.value.trim()) {
      errorTips.value = 2
      return
    } else if (!isAgree.value) {
      errorTips.value = 6
      return
    }
  } else {
    // 用户名密码
    if (!checkUserName(userName.value)) {
      errorTips.value = 3
      return
    } else if (!password.value.trim()) {
      errorTips.value = 4
      return
    } else if (!isAgree.value) {
      errorTips.value = 6
      return
    }
  }
  errorTips.value = 0
  const data = {
    userName: mobile.value ? mobile.value : userName.value,
    passWord: loginType.value === 0 ? encrypt(password.value) : validCode.value
  }
  if (!isLogging.value) {
    http({
      url: loginType.value === 0 ? '/login' : '/smsLogin',
      method: 'post',
      data
    }).then(({ data }) => {
      cookie.set('bbcToken', data.accessToken)
      userStore.initUser()
      // 登录完成后需要获取并更新是否为通联支付（开启通联支付后，会失效所有用户的token）
      http({
        url: '/sys/config/paySettlementType',
        method: 'get'
      }).then(({ data }) => {
        if (data) {
          localStorage.setItem('bbcPaySettlementType', data)
          // 通联支付请求完成之后，再刷新页面，防止页面刷新时，请求还未完成
          isLogging.value = true
          emit('hideLoginPop')
          window.location.pathname == '/register' ? router.push({ path: '/' }) : window.location.reload()
        }
      })
    })
  }
}, 600)

/**
 * 清除输入框内容
 */
const clearInput = (e) => {
  const type = e.target.dataset.type
  switch (type) {
    case 'mobile':
      mobile.value = ''
      break
    case 'userName':
      userName.value = ''
      break
    case 'password':
      password.value = ''
      break
    default:
      break
  }
}

/**
 * 跳转到《服务条款》或《隐私协议》
 */
const toTermsPage = (sts) => {
  router.push({
    path: '/terms-page',
    query: {
      sts
    }
  })
}
</script>

<style lang="scss" scoped>
@use "index";
</style>
